<template>
	<view class="container">
		<!-- 用户信息区域 -->
		<template v-if="isLogin">
			<view class="user-info">
				<view class="user-info-section">
					<view class="avatar-section">
						<image class="avatar" :src="userInfo.avatar ? 'http://localhost/dev-api' + userInfo.avatar : '/static/images/profile.jpg'" mode="aspectFill"></image>
					</view>
					<view class="info-section">
						<text class="nickname">{{userInfo.nickName || '未设置昵称'}}</text>
						<text class="phone" v-if="userInfo.phonenumber">{{userInfo.phonenumber}}</text>
						<text class="signature" v-if="userInfo.signature">{{userInfo.signature}}</text>
					</view>
				</view>
				<view class="user-actions">
					<view class="edit-btn" @click="goToEdit">
						<text>编辑资料</text>
					</view>
					<view class="edit-btn" @click="goToSettings">
						<text>设置</text>
					</view>
				</view>
			</view>
			
			<!-- 数据统计 -->
			<view class="user-stats">
				<view class="stat-item" @click="goToFollows">
					<text class="num">{{ userInfo && userInfo.followCount ? userInfo.followCount : 0 }}</text>
					<text class="label">关注</text>
				</view>
				<view class="stat-item" @click="goToFans">
					<text class="num">{{ userInfo && userInfo.fansCount ? userInfo.fansCount : 0 }}</text>
					<text class="label">粉丝</text>
				</view>
				<view class="stat-item" @click="goToLikes">
					<text class="num">{{ userInfo && userInfo.likeCount ? userInfo.likeCount : 0 }}</text>
					<text class="label">获赞与收藏</text>
				</view>
			</view>
			
			<!-- 内容区域 -->
			<view class="content-tabs">
				<view class="tab-header">
					<view 
						class="tab-item" 
						v-for="(tab, index) in tabs" 
						:key="index"
						:class="{ active: currentTab === index }"
						@click="switchTab(index)"
					>
						<text>{{ tab.name }}</text>
						<text v-if="tab.count" class="count">({{ tab.count }})</text>
					</view>
				</view>
				<view class="tab-content">
					<!-- 笔记列表 -->
					<view v-if="currentTab === 0" class="notes-list">
						<view v-if="notesLoading" class="empty-tip">
							<text>加载中...</text>
						</view>
						<view v-else-if="notes.length === 0" class="empty-tip">
							<text>还没有笔记哦，快去发布吧~</text>
						</view>
						<view v-else>
							<view v-for="item in notes" :key="item.taskId" class="collect-item" @click="goToTaskDetail(item.taskId)">
								<image class="collect-cover" :src="getFirstImageFromUrls(item.imageUrls)" mode="aspectFill"></image>
								<view class="collect-info">
									<text class="collect-title">{{ item.title || item.jobName }}</text>
									<text class="collect-time">{{ item.createTime }}</text>
								</view>
							</view>
						</view>
					</view>
					<!-- 收藏列表 -->
					<view v-if="currentTab === 1" class="collect-list">
						<view v-if="collectsLoading" class="empty-tip">
							<text>加载中...</text>
						</view>
						<view v-else-if="collects.length === 0" class="empty-tip">
							<text>还没有收藏内容哦~</text>
						</view>
						<view v-else>
							<view v-for="item in collects" :key="item.taskId" class="collect-item" @click="goToTaskDetail(item.taskId)">
								<image class="collect-cover" :src="getFirstImageFromUrls(item.imageUrls)" mode="aspectFill"></image>
								<view class="collect-info">
									<text class="collect-title">{{ item.title || item.jobName }}</text>
									<text class="collect-time">{{ item.createTime }}</text>
								</view>
							</view>
						</view>
					</view>
					<!-- 已报名列表 -->
					<view v-if="currentTab === 2" class="applied-list">
						<view v-if="appliedLoading" class="empty-tip">
							<text>加载中...</text>
						</view>
						<view v-else-if="appliedTasks.length === 0" class="empty-tip">
							<text>还没有已报名的任务哦~</text>
						</view>
						<view v-else>
							<view v-for="item in appliedTasks" :key="item.taskId" class="collect-item" @click="goToTaskDetail(item.taskId)">
								<image class="collect-cover" :src="getFirstImageFromUrls(item.imageUrls)" mode="aspectFill"></image>
								<view class="collect-info">
									<text class="collect-title">{{ item.title || item.jobName }}</text>
									<text class="collect-time">{{ item.createTime }}</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</template>
		
		<!-- 未登录状态 -->
		<template v-else>
			<view class="not-login">
				<image class="default-avatar" src="/static/images/profile.jpg" mode="aspectFill"></image>
				<view class="login-tips">登录后查看更多信息</view>
				<view class="login-btns">
					<button class="btn login-btn" @click="goToLogin">登录</button>
					<button class="btn register-btn" @click="goToRegister">注册</button>
				</view>
			</view>
		</template>
		
		<!-- 发布弹窗 -->
		<view v-if="showPublishPopup" class="custom-popup-mask" @click="closePublishPopup">
			<view class="custom-popup" @click.stop>
				<view class="popup-item" @click="onChooseAlbum">从相册选择</view>
				<view class="popup-item" @click="onTakePhoto">
					相机
					<text class="popup-desc">拍摄</text>
				</view>
				<view class="popup-item" @click="onTextGenerate">写文字</view>
				<view class="popup-cancel" @click="closePublishPopup">取消</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { mapGetters, mapActions } from 'vuex'
	import { getUserInfo } from '@/api/user.js'
	import { getCollectTasks, getTaskList, getAppliedTasks, getTaskStats } from '@/api/task.js'
	import config from '@/config/config.js'
	
	export default {
		data() {
			return {
				tabs: [
					{ name: '笔记', count: 0 },
					{ name: '收藏', count: 0 },
					{ name: '已报名', count: 0 }
				],
				currentTab: 0,
				notes: [],
				notesLoading: false,
				collects: [],
				collectsLoading: false,
				appliedTasks: [],
				appliedLoading: false,
				showPublishPopup: false,
				hasLoaded: {
					notes: false,
					collects: false,
					applied: false
				}
			}
		},
		computed: {
			...mapGetters('user', ['userInfo', 'isLogin'])
		},
		onLoad() {
			this.loadUserInfo()
			// 监听用户信息更新事件
			uni.$on('updateUserInfo', this.onUserInfoUpdate)
		},
		onUnload() {
			// 移除事件监听
			uni.$off('updateUserInfo', this.onUserInfoUpdate)
		},
		onShow() {
			this.loadUserInfo();
			if (this.isLogin) {
				this.loadNotes();
				this.loadCollects();
			}
		},
		mounted() {
			uni.onTabBarMidButtonTap(() => {
				const pages = getCurrentPages();
				if (pages.length > 0) {
					const currentPage = pages[pages.length - 1];
					if (currentPage.route === 'pages/tabbar/user/user') {
						this.showPublishPopup = true;
					}
				}
			});
		},
		methods: {
			...mapActions('user', ['setUserInfo']),
			// 加载用户信息
			async loadUserInfo() {
				try {
					const token = uni.getStorageSync('token')
					if (!token) {
						this.handleNotLogin()
						return
					}
					
					this.loadStats(); // 先加载统计数据
					
					const res = await getUserInfo({
						header: {
							'Authorization': token
						}
					})
					if (res.code === 200) {
						// 处理用户信息
						const userInfo = {
							...res.user,
							roles: res.roles,
							permissions: res.permissions
						}
						this.setUserInfo(userInfo)
						// 移除自动加载列表的逻辑
					} else {
						throw new Error(res.msg || '获取用户信息失败')
					}
				} catch (err) {
					console.error('获取用户信息失败:', err)
					uni.showToast({
						title: err.message || '获取用户信息失败',
						icon: 'none'
					})
					
					// 如果是未登录或token失效，显示未登录状态
					if (err.message === '未登录' || err.message.includes('认证失败')) {
						this.handleNotLogin()
					}
				}
			},
			// 处理未登录状态
			handleNotLogin() {
				// 清除本地存储
				uni.removeStorageSync('token')
				uni.removeStorageSync('userInfo')
				// 更新状态
				this.setUserInfo({})
			},
			// 跳转到登录页面
			goToLogin() {
				uni.navigateTo({
					url: '/pages/login/login'
				})
			},
			// 跳转到注册页面
			goToRegister() {
				uni.navigateTo({
					url: '/pages/register/register'
				})
			},
			// 切换标签页
			switchTab(index) {
				this.currentTab = index
				if (index === 0 && !this.hasLoaded.notes) {
					this.loadNotes()
				} else if (index === 1 && !this.hasLoaded.collects) {
					this.loadCollects()
				} else if (index === 2 && !this.hasLoaded.applied) {
					this.loadAppliedTasks()
				}
			},
			// 跳转到编辑资料
			goToEdit() {
				uni.navigateTo({
					url: '/pages/user/edit'
				})
			},
			// 跳转到关注列表
			goToFollows() {
				uni.navigateTo({
					url: '/pages/user/follows'
				})
			},
			// 跳转到粉丝列表
			goToFans() {
				uni.navigateTo({
					url: '/pages/user/fans'
				})
			},
			// 跳转到获赞与收藏
			goToLikes() {
				uni.navigateTo({
					url: '/pages/user/likes'
				})
			},
			// 跳转到设置
			goToSettings() {
				uni.navigateTo({
					url: '/pages/user/settings'
				})
			},
			// 用户信息更新事件处理
			onUserInfoUpdate(newUserInfo) {
				this.setUserInfo(newUserInfo)
			},
			// 加载收藏任务列表
			async loadCollects() {
				this.collectsLoading = true;
				try {
					const token = uni.getStorageSync('token');
					if (!token) {
						this.collects = [];
						return;
					}
					const res = await getCollectTasks();
					if (res.code === 200) {
						this.collects = res.rows || [];
						this.hasLoaded.collects = true; // 标记已加载
					}
				} catch (e) {
					this.collects = [];
					uni.showToast({ title: '获取收藏失败', icon: 'none' });
				} finally {
					this.collectsLoading = false;
				}
			},
			goToTaskDetail(taskId) {
				// 检查当前用户是否为任务发布者
				const currentTask = this.notes.find(task => task.taskId == taskId) || 
								   this.collects.find(task => task.taskId == taskId) || 
								   this.appliedTasks.find(task => task.taskId == taskId);
				if (currentTask && this.userInfo && currentTask.createBy == this.userInfo.userId) {
					// 如果是发布者，跳转到管理页面
					uni.navigateTo({
						url: `/pages/task-manage/task-manage?taskId=${taskId}`
					});
				} else {
					// 如果是普通用户，跳转到详情页面
					uni.navigateTo({
						url: `/pages/task-detail/task-detail?taskId=${taskId}`
					});
				}
			},
			getFirstImageFromUrls(urls) {
				if (!urls) return '';
				const arr = urls.split(',');
				if (arr[0]) {
					if (/^https?:\/\//.test(arr[0])) {
						return arr[0];
					} else {
						return config.baseUrl + config.apiPrefix + arr[0];
					}
				}
				return '';
			},
			// 加载本人发布的任务
			async loadNotes() {
				this.notesLoading = true;
				try {
					const res = await getTaskList();
					if (res.code === 200) {
						this.notes = res.rows || [];
						this.hasLoaded.notes = true; // 标记已加载
					}
				} catch (e) {
					uni.showToast({ title: '获取任务失败', icon: 'none' });
				} finally {
					this.notesLoading = false;
				}
			},
			// 加载已报名任务列表
			async loadAppliedTasks() {
				this.appliedLoading = true;
				try {
					const res = await getAppliedTasks();
					if (res.code === 200) {
						this.appliedTasks = res.rows || [];
						this.hasLoaded.applied = true; // 标记已加载
					}
				} catch (e) {
					uni.showToast({ title: '获取已报名任务失败', icon: 'none' });
				} finally {
					this.appliedLoading = false;
				}
			},
			// 新增：加载统计数据
			async loadStats() {
				const res = await getTaskStats();
				if (res.code === 200 && res.data) {
					this.tabs[0].count = res.data.notesCount || 0;
					this.tabs[1].count = res.data.collectsCount || 0;
					this.tabs[2].count = res.data.appliedCount || 0;
				}
			},
			closePublishPopup() {
				this.showPublishPopup = false;
			},
			onChooseAlbum() {
				this.closePublishPopup();
				uni.chooseImage({
					count: 1,
					sourceType: ['album'],
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0];
						uni.navigateTo({
							url: '/pages/tabbar/publish/publish?image=' + encodeURIComponent(tempFilePath)
						});
					}
				});
			},
			onTakePhoto() {
				this.closePublishPopup();
				uni.chooseImage({
					count: 1,
					sourceType: ['camera'],
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0];
						uni.navigateTo({
							url: '/pages/tabbar/publish/publish?image=' + encodeURIComponent(tempFilePath)
						});
					}
				});
			},
			onTextGenerate() {
				this.closePublishPopup();
				uni.navigateTo({
					url: '/pages/text-input/text-input'
				});
			}
		}
	}
</script>

<style>
	.container {
		min-height: 100vh;
		background-image: url('@/static/images/background.jpeg');
		background-size: cover;
		background-position: center;
		background-repeat: no-repeat;
	}
	
	.user-info {
		padding: 30rpx;
		margin: 20rpx;
		background-color: rgba(255, 255, 255, 0.9);
		border-radius: 20rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
	}
	
	.user-info-section {
		display: flex;
		align-items: center;
		padding: 20rpx;
		margin-bottom: 30rpx;
	}
	
	.avatar-section {
		position: relative;
		margin-right: 30rpx;
	}
	
	.avatar {
		width: 140rpx;
		height: 140rpx;
		border-radius: 70rpx;
		border: 4rpx solid #fff;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}
	
	.info-section {
		flex: 1;
		display: flex;
		flex-direction: column;
	}
	
	.nickname {
		font-size: 36rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 16rpx;
	}
	
	.phone {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 12rpx;
	}
	
	.signature {
		font-size: 26rpx;
		color: #999;
		line-height: 1.4;
	}
	
	.user-actions {
		display: flex;
		justify-content: flex-end;
		margin-top: 20rpx;
		padding: 0 20rpx;
	}
	
	.edit-btn {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		padding: 12rpx 32rpx;
		border: none;
		border-radius: 30rpx;
		font-size: 26rpx;
		color: #fff;
		background: linear-gradient(to right, #409EFF, #64B5F6);
		box-shadow: 0 2rpx 8rpx rgba(64, 158, 255, 0.3);
		margin-left: 20rpx;
		transition: all 0.3s ease;
	}
	
	.edit-btn:active {
		transform: scale(0.98);
		box-shadow: 0 1rpx 4rpx rgba(64, 158, 255, 0.2);
	}
	
	.user-stats {
		display: flex;
		padding: 30rpx;
		margin: 20rpx;
		background-color: rgba(255, 255, 255, 0.9);
		border-radius: 20rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
	}
	
	.stat-item {
		flex: 1;
		text-align: center;
		position: relative;
	}
	
	.stat-item:not(:last-child):after {
		content: '';
		position: absolute;
		right: 0;
		top: 50%;
		transform: translateY(-50%);
		height: 50%;
		width: 2rpx;
		background-color: #eee;
	}
	
	.stat-item .num {
		display: block;
		font-size: 36rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 8rpx;
	}
	
	.stat-item .label {
		font-size: 24rpx;
		color: #666;
	}
	
	.feature-list {
		background-color: #fff;
		margin-bottom: 20rpx;
	}
	
	.feature-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx;
		border-bottom: 1rpx solid #f5f5f5;
	}
	
	.feature-left {
		display: flex;
		align-items: center;
	}
	
	.feature-title {
		margin-left: 20rpx;
		font-size: 28rpx;
		color: #333;
	}
	
	.content-tabs {
		background-color: #fff;
	}
	
	.tab-header {
		display: flex;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
	}
	
	.tab-item {
		flex: 1;
		text-align: center;
		font-size: 28rpx;
		color: #666;
		position: relative;
	}
	
	.tab-item.active {
		color: #333;
		font-weight: bold;
	}
	
	.tab-item.active:after {
		content: '';
		position: absolute;
		bottom: -20rpx;
		left: 50%;
		transform: translateX(-50%);
		width: 40rpx;
		height: 4rpx;
		background-color: #333;
	}
	
	.count {
		font-size: 24rpx;
		color: #999;
		margin-left: 4rpx;
	}
	
	.empty-tip {
		padding: 100rpx 0;
		text-align: center;
		color: #999;
		font-size: 28rpx;
	}
	
	.edit-btn {
		display: inline-block;
		padding: 10rpx 30rpx;
		border: 1rpx solid #ddd;
		border-radius: 30rpx;
		font-size: 26rpx;
		color: #333;
		text-align: center;
		min-width: 120rpx;
		margin: 0 10rpx;
	}
	
	.edit-btn text {
		display: inline-block;
		width: 100%;
		text-align: center;
	}
	
	.not-login {
		background-color: #fff;
		padding: 60rpx 30rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	
	.default-avatar {
		width: 160rpx;
		height: 160rpx;
		border-radius: 80rpx;
	}
	
	.login-tips {
		margin: 30rpx 0;
		font-size: 28rpx;
		color: #999;
	}
	
	.login-btns {
		display: flex;
		justify-content: center;
		margin-top: 20rpx;
	}
	
	.btn {
		margin: 0 20rpx;
		width: 240rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		border-radius: 40rpx;
		font-size: 28rpx;
	}
	
	.login-btn {
		background-color: #409EFF;
		color: #fff;
	}
	
	.register-btn {
		background-color: #fff;
		color: #409EFF;
		border: 1rpx solid #409EFF;
	}
	
	.collect-item {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
		cursor: pointer;
	}
	
	.collect-cover {
		width: 120rpx;
		height: 120rpx;
		border-radius: 12rpx;
		margin-right: 20rpx;
		object-fit: cover;
	}
	
	.collect-info {
		flex: 1;
		display: flex;
		flex-direction: column;
	}
	
	.collect-title {
		font-size: 30rpx;
		color: #333;
		font-weight: bold;
		margin-bottom: 10rpx;
	}
	
	.collect-time {
		font-size: 24rpx;
		color: #999;
	}
	
	.custom-popup-mask {
		position: fixed;
		left: 0; right: 0; top: 0; bottom: 0;
		background: rgba(0,0,0,0.3);
		z-index: 9999;
		display: flex;
		align-items: flex-end;
	}
	.custom-popup {
		width: 100vw;
		background: #fff;
		border-radius: 24rpx 24rpx 0 0;
		padding-bottom: 40rpx;
	}
	.popup-item {
		padding: 40rpx 0 20rpx 0;
		text-align: center;
		font-size: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
		position: relative;
	}
	.popup-desc {
		display: block;
		font-size: 20rpx;
		color: #999;
		margin-top: 8rpx;
	}
	.popup-cancel {
		padding: 40rpx 0 0 0;
		text-align: center;
		font-size: 30rpx;
		color: #007aff;
	}
</style>
